/*
 * @(#)Identity.java	1.29 01/12/12
 *
 * 版权所有2002 Sun Microsystems，股份有限公司保留所有权利。SUN专有/保密。使用须遵守许可条款。
 */
 
package java.security;

import java.io.Serializable;
import java.util.*;

/**
 * <p>此类表示身份：可以使用其公钥对其身份进行身份验证的真实世界对象，如个人、公司或组织。
 * 身份也可以是更抽象(或具体)的构造，如守护程序线程或智能卡。
 *
 * 所有标识对象都有一个名称和一个公钥。名字是不变的。也可以对身份进行作用域划分。
 * 也就是说，如果身份被指定为具有特定作用域，则该身份的名称和公钥在该作用域中是唯一的。
 *
 * 身份还具有一组证书(所有证书都证明其自己的公钥)。这些证书中指定的主体名称不必相同，只需密钥即可。
 *
 * <p>身份可以细分为子类别，包括邮政和电子邮件地址、电话号码、面孔和徽标的图像等。
 *
 * @see IdentityScope
 * @see Signer
 * @see Principal
 *
 * @version 	1.24, 01/27/97
 * @author Benjamin Renaud 
 */
public abstract 
class Identity implements Principal, Serializable {

    /**
     * The name for this identity.
     */
    private String name;

    /**
     * The public key for this identity.
     */
    private PublicKey publicKey;

    /**
     * Generic, descriptive information about the identity.
     */
    String info = "No further information available.";

    /**
     * The scope of the identity.
     */
    IdentityScope scope;

    /**
     * The certificates for this identity.
     */
    Vector certificates;

    /**
     * Constructor for serialization only.
     */
    protected Identity() {
	this("restoring...");
    }

    /**
     * Constructs an identity with the specified name and scope.
     *
     * @param name the identity name.  
     * @param scope the scope of the identity.
     *
     * @exception KeyManagementException if there is already an identity 
     * with the same name in the scope.
     */
    public Identity(String name, IdentityScope scope) throws
    KeyManagementException {
	this(name);
	this.scope = scope;
    }

    /**
     * Constructs an identity with the specified name and no scope.
     *
     * @param name the identity name.
     */
    public Identity(String name) {
	this.name = name;
    }

    /**
     * Returns this identity's name.
     *
     * @return the name of this identity.
     */
    public final String getName() {
	return name;
    }

    /**
     * Returns this identity's scope.
     *
     * @return the scope of this identity.
     */
    public final IdentityScope getScope() {
	return scope;
    }

    /**
     * Returns this identity's public key.
     * 
     * @return the public key for this identity.
     */
    public PublicKey getPublicKey() {
	return publicKey;
    }

    /**
     * 设置此身份的公钥。此操作将删除旧密钥和此身份的所有证书。
     *
     * @param key the public key for this identity.
     *
     * @exception KeyManagementException 如果标识作用域中的另一个标识具有相同的公钥，或者如果发生另一个异常。
     */
    /* Should we throw an exception if this is already set? */
    public void setPublicKey(PublicKey key) throws KeyManagementException {
	
	check("set.public.key");
	this.publicKey = key;
	certificates = new Vector();
    }

    /**
     * Specifies a general information string for this identity.
     *
     * @param info the information string.
     *
     * @see #getInfo
     */
    public void setInfo(String info) {
	check("set.info");
	this.info = info;
    }

    /**
     * Returns general information previously specified for this identity.
     *
     * @return general information about this identity.
     *
     * @see #setInfo
     */
    public String getInfo() {
	return info;
    }

    /**
     * 为此身份添加证书。如果身份具有公钥，则证书中的公钥必须相同，如果身份没有公钥，则将身份的公钥设置为证书中指定的公钥。
     *
     * @param certificate the certificate to be added.
     *
     * @exception KeyManagementException 如果证书无效，如果要添加的证书中的公钥与此身份的公钥冲突，或者如果发生另一个异常。
     */
    public void addCertificate(Certificate certificate)
    throws KeyManagementException {

	check("add.certificate");

	if (certificates == null) {
	    certificates = new Vector();
	}
	if (publicKey != null) {
	    if (!keyEquals(publicKey, certificate.getPublicKey())) {
		throw new KeyManagementException(
		    "public key different from cert public key");
	    }
	} else {
	    publicKey = certificate.getPublicKey();
	}
	certificates.addElement(certificate);
    }

   private boolean keyEquals(Key aKey, Key anotherKey) {
	if (aKey.getFormat().equalsIgnoreCase(anotherKey.getFormat())) {
	    return MessageDigest.isEqual(aKey.getEncoded(), 
					 anotherKey.getEncoded());
	} else {
	    return false;
	}
    }


    /**
     * Removes a certificate from this identity.
     *
     * @param certificate the certificate to be removed.
     *
     * @exception KeyManagementException if the certificate is
     * missing, or if another exception occurs.
     */
    public void removeCertificate(Certificate certificate)
    throws KeyManagementException {
	check("remove.certificate");
	if (certificates != null) {
	    certificates.removeElement(certificate);
	}
    }

    /**
     * Returns a copy of all the certificates for this identity.  
     * 
     * @return a copy of all the certificates for this identity.  
     */
    public Certificate[] certificates() {
	if (certificates == null) {
	    return new Certificate[0];
	}
	int len = certificates.size();
	Certificate[] certs = new Certificate[len];
	certificates.copyInto(certs);
	return certs;
    }

    /**
     * 测试指定对象和此标识之间的等价性。这首先测试实体是否引用相同的对象，在这种情况下，它返回TRUE。
	 * 接下来，它检查实体是否具有相同的名称和相同的作用域。如果是，则该方法返回TRUE。
	 * 否则，它会调用<a href>idetyEquals</a>，子类应该覆盖这些子类。
     *
     * @param identity the object to test for equality with this identity.  
     *
     * @return true if the objects are considered equal, false otherwise.
     *
     * @see #identityEquals 
     */
    public final boolean equals(Object identity) {

	if (identity == this) {
	    return true;
	}

	if (identity instanceof Identity) {
	    Identity i = (Identity)identity;
	    if (i.getScope() == scope && i.getName().equals(name)) {
		return true;
	    } else {
		return identityEquals(i);	    
	    }
	}
	return false;
    }

    /**
     * 测试指定标识和此标识之间的等价性。此方法应由子类重写以测试相等性。如果名称和公钥相等，则默认行为是返回True。
     *
     * @param identity the identity to test for equality with this identity.
     * 
     * @return true if the identities are considered equal, false
     * otherwise. 
     *
     * @see #equals 
     */
    protected boolean identityEquals(Identity identity) {
	return (name.equals(identity.name) && 
		publicKey.equals(identity.publicKey));
    }

    /**
     * Returns a parsable name for identity: identityName.scopeName
     */
    String fullName() {
	String parsable = name;
	if (scope != null) {
	    parsable += "." + scope.getName();
	}
	return parsable;
    }

    /**
     * 返回描述此标识的短字符串，告知其名称及其作用域(如果有)。
     *
     * @return 有关此身份的信息，例如其名称及其作用域的名称(如果有)。
     */
    public String toString() {
	check("print");
	String printable = name;
	if (scope != null) {
	    printable += "[" + scope.getName() + "]";
	}
	return printable;
    }

    /**
     * 返回此标识的字符串表示形式，可选地具有比不带任何参数的<code>toString</code>方法提供的更多详细信息。
     *
     * @param detailed whether or not to provide detailed information.  
     *
     * @return 有关此身份的信息。如果<code>Detail</code>为True，
	 * 则此方法返回的信息比不带任何参数的<code>toString</code>方法提供的信息多。
     *
     * @see #toString
     */
    public String toString(boolean detailed) {
	String out = toString();
	if (detailed) {
	    out += "\n";
	    out += printKeys();
	    out += "\n" + printCertificates();
	    if (info != null) {
		out += "\n\t" + info;
	    } else {
		out += "\n\tno additional information available.";
	    }
	}	  
	return out;
    }

    String printKeys() {
	String key = "";
	if (publicKey != null) {
	    key = "\tpublic key initialized";
	} else {
	    key = "\tno public key";
	}
	return key;
    }

    String printCertificates() {
	String out = "";
	if (certificates == null) {
	    return "\tno certificates";
	} else {
	    out += "\tcertificates: \n";
	    Enumeration e = certificates.elements();
	    int i = 1;
	    while (e.hasMoreElements()) {
		Certificate cert = (Certificate)e.nextElement();
		out += "\tcertificate " + i++ +
		    "\tfor  : " + cert.getPrincipal() + "\n";
		out += "\t\t\tfrom : " + 
		    cert.getGuarantor() + "\n";
	    }
	}
	return out;
    }
    
    /**
     * Returns a hashcode for this identity.
     *
     * @return a hashcode for this identity.
     */
    public int hashCode() {
	String scopedName = name;
	if (scope != null) {
	    scopedName += scope.getName();
	}
	return scopedName.hashCode();
    }

    void check(String directive) {
	staticCheck(this.getClass().getName() + "." + directive + "." +fullName());
    }

    static void staticCheck(String directive) {
	SecurityManager security = System.getSecurityManager();
	if (security != null) {
	    security.checkSecurityAccess(directive);
	}
    }
}

